<template>
  <div>
    <div class="top-panel">
      <el-card>
        <el-form
          ref="searchForm"
          :model="searchForm"
          label-width="80px"
          label-position="right"
        >
          <el-row>
            <el-col :span="5">
              <el-form-item label="账号" size="small">
                <el-input
                  class="password-input"
                  v-model="searchForm.accountFuzzy"
                  clearable
                  placeholder="支持模糊搜索"
                  @keyup.enter.native="loadDataList"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="手机号" size="small">
                <el-input
                  class="password-input"
                  v-model="searchForm.phoneFuzzy"
                  clearable
                  placeholder="支持模糊搜索"
                  @keyup.enter.native="loadDataList"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col
              :span="4"
              :style="{ paddingLeft: '10px', 'padding-top': '3px' }"
            >
              <el-button type="success" size="mini" @click="loadDataList()"
                >查询</el-button
              >
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-button
                v-has="permissionCode.edit"
                type="primary"
                size="mini"
                @click="showEdit('add')"
                >新增账号</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <el-card>
      <Table
        :columns="columns"
        :fetch="loadDataList"
        :dataSource="tableData"
        :options="tableOptions"
      >
      </Table>
    </el-card>
    <Dialog
      :title="editDialogInfo.title"
      :buttons="editDialogInfo.buttons"
      :visible="editDialogInfo.show"
      @close="editDialogInfo.show = false"
      :width="'700px'"
    >
      <el-form
        ref="editForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName" size="small">
              <el-input :maxLength="10" v-model="formData.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号" prop="account" size="small">
              <el-input :maxLength="20" v-model="formData.account" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              size="small"
              label="密码"
              prop="password"
              v-if="!editDialogInfo.edit"
            >
              <el-input
                type="password"
                :maxLength="20"
                v-model="formData.password"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              size="small"
              label="重复密码"
              prop="rePassword"
              v-if="!editDialogInfo.edit"
            >
              <el-input
                type="password"
                :maxLength="20"
                v-model="formData.rePassword"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item size="small" label="手机号" prop="phone">
              <el-input
                :maxLength="11"
                v-model="formData.phone"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item size="small" label="邮箱" prop="email">
              <el-input :maxLength="20" v-model="formData.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :span="12">
          <el-form-item label="职位" size="small" prop="position">
            <el-input :maxLength="20" v-model="formData.position" />
          </el-form-item>
        </el-row>
        <el-row :span="24">
          <el-col>
            <el-form-item label="角色" size="small" prop="roles">
              <el-checkbox-group v-model="formData.roles">
                <span
                  class="check-span-item"
                  v-for="(item, index) in roleList"
                  :key="index"
                >
                  <el-checkbox :label="item.roleId + ''">
                    {{ item.roleName }}
                  </el-checkbox>
                </span>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </Dialog>

    <Dialog
      ref="editDialog4Pass"
      :title="editDialogInfo4Pass.title"
      :buttons="editDialogInfo4Pass.buttons"
      :visible="editDialogInfo4Pass.show"
      @close="editDialogInfo4Pass.show = false"
    >
      <el-form
        ref="editForm4Pass"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item size="small" label="密码" prop="password">
          <el-input
            type="password"
            :maxLength="20"
            v-model="formData.password"
          />
        </el-form-item>
        <el-form-item size="small" label="重复密码" prop="rePassword">
          <el-input
            type="password"
            :maxLength="20"
            v-model="formData.rePassword"
          />
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>
<script>
export default {
  data() {
    let validateRePass = (rule, value, callback) => {
      if (value !== this.formData.password) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }

    return {
      permissionCode: {
        edit: 'settings_account_edit',
        del: 'settings_account_del',
        opStatus: 'settings_account_op_status',
        updatePassword: 'settings_account_update_password',
      },
      tableData: {},
      tableOptions: {
        topHeight: 88,
      },
      columns: [
        {
          label: '用户名',
          prop: 'userName',
          width: 150,
        },
        {
          label: '账号',
          prop: 'account',
          width: 150,
        },
        {
          label: '手机',
          prop: 'phone',
          width: 200,
        },
        {
          label: '拥有角色',
          prop: 'roleName',
        },
        {
          label: '创建时间',
          prop: 'createTime',
          width: 200,
        },
        {
          label: '状态',
          prop: 'status',
          width: 100,
          render: (row, index) => {
            return (
              <div class="table-list-op-btns">
                {row.status == 0 ? (
                  <span style="color:red">禁用</span>
                ) : (
                  <span style="color:green">启用</span>
                )}
              </div>
            )
          },
        },
        {
          label: '操作',
          prop: 'operation',
          width: 250,
          render: (row, index) => {
            return (
              <div class="table-list-op-btns">
                <span v-has={this.permissionCode.edit}>
                  <a
                    href="javascript:void(0)"
                    onClick={() => this.showEdit('edit', row)}
                  >
                    修改
                  </a>
                </span>
                <span v-has={this.permissionCode.del}>
                  <a
                    href="javascript:void(0)"
                    onClick={() => this.delAccount(row)}
                  >
                    删除
                  </a>
                </span>
                <span v-has={this.permissionCode.updatePassword}>
                  <a
                    href="javascript:void(0)"
                    onClick={() => this.showEdit4Pass(row)}
                  >
                    修改密码
                  </a>
                </span>
                <span v-has={this.permissionCode.opStatus}>
                  <a
                    href="javascript:void(0)"
                    onClick={() => this.changeAccountStatus(row)}
                  >
                    {row.status == 0 ? '启用' : '禁用'}
                  </a>
                </span>
              </div>
            )
          },
        },
      ],
      api: {
        loadDataList: '/settings/loadAccountList',
        loadAllRoles: '/settings/loadAllRoles',
        saveAccount: '/settings/saveAccount',
        delAccount: '/settings/delAccount',
        updatePassword: '/settings/updatePassword',
        updateStatus: '/settings/updateStatus',
      },
      editDialogInfo: {
        title: '新增账号',
        buttons: [
          {
            type: 'primary',
            text: '确定',
            click: (e) => {
              this.submitForm(e)
            },
          },
        ],
        show: false,
      },
      editDialogInfo4Pass: {
        title: '修改密码',
        buttons: [
          {
            type: 'primary',
            text: '确定',
            click: (e) => {
              this.submitForm4Pass(e)
            },
          },
        ],
        show: false,
      },
      formData: {
        roles: [],
      },
      rules: {
        userName: [{ required: true, message: '请输入用户名' }],
        account: [
          { required: true, message: '请输入账号' },
          {
            validator: this.Verify.account,
            message: '账号只能数字，字母下滑线',
          },
        ],
        password: [
          { required: true, message: '请输入密码' },
          {
            validator: this.Verify.password,
            message: '密码最少8位，只能数字字母和特殊字符',
          },
        ],
        rePassword: [
          { required: true, message: '请再次输入密码' },
          {
            validator: validateRePass,
            message: '两次输入的密码不一致',
          },
        ],
        phone: [
          { required: true, message: '请输入手机号' },
          {
            validator: this.Verify.phone,
            trigger: 'blur',
            message: '请输入正确的手机号',
          },
        ],
        email: [
          {
            validator: this.Verify.email,
            trigger: 'blur',
            message: '请输入正确的邮箱',
          },
        ],
        roles: [{ required: true, message: '请选择角色' }],
      },
      roleList: [],
      searchForm: {},
    }
  },
  methods: {
    async loadDataList() {
      let params = {
        pageNo: this.tableData.pageNo,
        pageSize: this.tableData.pageSize,
      }
      Object.assign(params, this.searchForm)

      let result = await this.Request({
        url: this.api.loadDataList,
        params: params,
      })
      this.tableData = result
    },

    //展示表单
    async showEdit(type, data) {
      // this.$refs.editForm.resetFields()
      this.editDialogInfo.show = true
      let roleList = await this.Request({
        url: this.api.loadAllRoles,
      })
      this.roleList = roleList

      this.$nextTick(async () => {
        if (this.$refs['editForm'] !== undefined) {
          this.$refs['editForm'].resetFields()
        }
        if (type === 'add') {
          this.editDialogInfo.edit = false
          this.editDialogInfo.title = '新增账号'
          this.formData = {
            roles: [],
          }
        } else {
          this.editDialogInfo.edit = true
          this.editDialogInfo.title = '修改账号'
          let editData = Object.assign({}, data)
          editData.roles = editData.roles.split(',')
          delete editData.createTime
          this.formData = editData
        }
      })
    },
    //提交表单
    async submitForm(e) {
      e.preventDefault()
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) {
          return false
        }
        let params = {}
        Object.assign(params, this.formData)
        params.roles = params.roles.join(',')
        await this.Request({
          url: this.api.saveAccount,
          params: params,
        })
        this.editDialogInfo.show = false
        this.$message.success('保存成功')
        this.loadDataList()
      })
    },
    //删除用户
    delAccount(data) {
      this.$confirm(`确认要删除【${data.userName}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await this.Request({
            url: this.api.delAccount,
            params: {
              userId: data.userId,
            },
          })
          this.$message.success('删除成功')
          this.loadDataList()
        })
        .catch(() => {})
    },
    //修改密码
    async showEdit4Pass(data) {
      this.editDialogInfo4Pass.show = true
      this.$nextTick(async () => {
        if (this.$refs['editForm4Pass'] !== undefined) {
          this.$refs['editForm4Pass'].resetFields()
        }
        this.editDialogInfo4Pass.title = '修改密码'
        this.formData = {
          userId: data.userId,
          roles: [],
        }
      })
    },

    async submitForm4Pass(e) {
      e.preventDefault()
      this.$refs.editForm4Pass.validate(async (valid) => {
        if (!valid) {
          return false
        }
        let params = {}
        Object.assign(params, this.formData)
        await this.Request({
          url: this.api.updatePassword,
          params: params,
        })
        this.$refs.editDialog4Pass.close()
        this.$message.success('修改成功')
        this.loadDataList()
      })
    },

    changeAccountStatus(data) {
      let status = data.status == 0 ? 1 : 0
      let info = status == 0 ? '禁用' : '启用'
      this.$confirm(`确认要【${info}】【${data.userName}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await this.Request({
            url: this.api.updateStatus,
            params: {
              userId: data.userId,
              status: status,
            },
          })
          this.$message.success('操作成功')
          this.loadDataList()
        })
        .catch(() => {})
    },
  },

  created() {},
}
</script>
<style lang="less" scoped>
.check-span-item {
  float: left;
  width: 30%;
  line-height: 20px;
}
</style>
